from django.shortcuts import render, HttpResponse
import hmac, hashlib
from django.views.decorators.csrf import csrf_exempt
import os, logging

APP_KEY = b'123456'
logging.basicConfig(level=logging.INFO,
            format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
            datefmt='%a, %d %b %Y %H:%M:%S',
            filename='/tmp/apiserver.log',
            filemode='w')

@csrf_exempt
def blogupdate(request):
    if request.method == "POST":
        signature = 'sha1=' + hmac.new(APP_KEY, request.body, hashlib.sha1).hexdigest()
        if request.META.get('HTTP_X_HUB_SIGNATURE') == signature:
            if request.META.get('HTTP_X_GITHUB_EVENT') == 'ping':
                return HttpResponse("test is ok")
            elif request.META.get('HTTP_X_GITHUB_EVENT') == 'push':
                os.chdir('/home/python/nginx/blog/')
                os.system('git fetch origin gh-pages')
                os.system('git reset --hard origin/gh-pages')
                logging.info("blog branch gh-pages is pull success!")
                return HttpResponse("branch gh-pages has already newest!")
            else:
                return HttpResponse("TypeError")
        else:
            return HttpResponse("AuthError")
    else:
        return HttpResponse("MethodError")
